require('express-async-errors');

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser = require('body-parser');
var timeout = require("connect-timeout");

global.Constant = require('./constant/constant');
global.Common = require('./common/common'); //公用的方法文件
global.async = require('async');
global.sid = require('js-shortid');
global.dateFormat = require('dateformat');
global.appRequire = function (thisPath) {
	return require(path.resolve(__dirname, thisPath))
}

// 从数据库加载Authorization和系统配置（异步）
const tokenHelper = appRequire('common/tokenHelper');

// 初始化系统配置缓存（包含课件价格模式等）
tokenHelper.initConfigCache();

// 加载Authorization
tokenHelper.getAuthorization().then(auth => {
	global.Authorization = auth;
	console.log('✓ Authorization已从数据库加载');
}).catch(err => {
	console.error('❌ 加载Authorization失败:', err.message);
	// 如果加载失败，使用默认值
	global.Authorization = "27dc0fce-498a-41f3-aa05-b0b55c2b40e8";
});

//var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');
var userRouter = require('./routes/user');
var txMac = require('./routes/txMac'); //腾讯相关服务
var wx = require('./routes/wx'); //微信相关服务

// 引入Token验证中间件
const verifyMiddleware = require('./routes/middleware/verify');

//定时任务
require('./routes/schedule/freeUserPpt');

var app = express();
app.use(cookieParser());
app.use(timeout("600s"));
// 使用Express内置的body parser
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: true }));

app.use('/exlceFile', express.static('./exlceFile'));
app.use('/imageFile', express.static('./imageFile'));
app.use('/imageNoUseFile', express.static('./imageNoUseFile'));
app.use('/MP_verify_8i79jWH9jBIdRn7X.txt', express.static('./MP_verify_8i79jWH9jBIdRn7X.txt'));
app.use('/m962bUhdF7.txt', express.static('./m962bUhdF7.txt'));
app.use('/WxjDZGVbj9.txt', express.static('./WxjDZGVbj9.txt'));

app.use(cors({
	origin: [
		'http://localhost:8080', 'http://localhost:8081', 'http://localhost:8082', 'http://localhost:8083', 'http://localhost:8084',
		'https://api.jimuzhou.com', 'https://www.jimuzhou.com', 'https://web.jimuzhou.top', 'https://pc.jimuzhou.top', "https://orderpreview.jimuzhou.top",
		'https://poster.jimuzhou.cloud', "https://artadmin.jimuzhou.cloud", "https://artppt.jimuzhou.cloud"
	], //指定接收的地址
	methods: ['GET', 'POST'], //指定接收的请求类型
	alloweHeaders: ['Content-Type', 'Authorization'] //指定header（修复拼写错误）
}))

app.use(logger('dev'));
// 移除重复的body parser配置，已在上面配置过

//app.use('/', indexRouter);
app.use('/admin', adminRouter);
app.use('/user', userRouter);//用户相关
app.use('/txMac', txMac); //腾讯相关服务
app.use('/wx', wx); //微信相关服务

// catch 404 and forward to error handler
app.use(function (req, res, next) {
	next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
	// set locals, only providing error in development
	res.locals.message = err.message;
	res.locals.error = req.app.get('env') === 'development' ? err : {};

	// render the error page
	res.status(err.status || 500);
	res.json({
		msg: err.message || "",
		code: err.status || 500
	});
});

module.exports = app;
